import binascii, os
import struct


def soft_crc32_st(pbuf, size, crc_value):
    st_const_value = 0x04C11DB7
    # crc_value = 0xFFFFFFFF
    for i in range(size):
        xbit = 0x80000000
        for bits in range(32):
            if crc_value & 0x80000000:
                crc_value <<= 1
                crc_value ^= st_const_value
            else:
                crc_value <<= 1
            if pbuf[i] & xbit:
                crc_value ^= st_const_value
            xbit >>= 1

    return crc_value & 0xFFFFFFFF

def compute_crc32(file_path):
    crc = 0xFFFFFFFF
    with open(file_path, 'rb') as file:
        while True:
            buffer = file.read(1024)
            if not buffer:
                break
            # crc = binascii.crc32(buffer, crc)
            pbuf = []
            for i in range(0, len(buffer), 4):
                value = (buffer[i] << 0) | (buffer[i+1] << 8) | (buffer[i+2] << 16) | (buffer[i+3] << 24)
                pbuf.append(value)
            _len = int(len(buffer) / 4)
            crc = soft_crc32_st(pbuf, _len, crc)
    
    return crc & 0xFFFFFFFF



file_path = 'Objects\Project.bin'

#计算长度
file_size = os.path.getsize(file_path)
# print(f"Size = {file_size}")

rem = file_size % 256
if (rem > 0):
    rem = 256 - rem
# print(f"Rem = {rem}")

# 长度补足
with open(file_path, 'ab') as file:
    file.write(struct.pack('B', 0) * rem)
    file.close()
# print(f"Size = {os.path.getsize(file_path)}")


# 计算文件crc32
crc_value = compute_crc32(file_path)
# print(f"CRC32 = {crc_value:08X}")

# 追加crc32校验

with open(file_path, 'ab') as file:
    file.write(struct.pack('1I', crc_value))

print("Add crc32 ok!")